//
//  LocalDataManager.m
//  OrangeNote
//
//  Created by 刘崇龙 on 16/1/23.
//  Copyright © 2016年 崇龙. All rights reserved.
//

#import "LocalDataManager.h"
#import "FMDB.h"
#import "NoteModel.h"
#import <UIKit/UIKit.h>
#import "NotebookModel.h"

static LocalDataManager *dataBase = nil;
static FMDatabase *db = nil;
@implementation LocalDataManager

+(instancetype)sharedDataBase{
    
    @synchronized(self) {
        
        if (nil == dataBase) {
            dataBase = [[LocalDataManager alloc]init];
            [dataBase openDB];
        }
    }
    return dataBase;
}

// 打开数据库
- (void)openDB{
    
    if (nil != db) {
        return;
    }
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@",documentPath);
    documentPath = [documentPath stringByAppendingPathComponent:@"/note.sqlite"];
    
    db = [FMDatabase databaseWithPath:documentPath];
    
    if ([db open]) {
        
        BOOL result1 =[db executeUpdate:@"CREATE TABLE IF NOT EXISTS Note ('ID' TEXT PRIMARY KEY NOT NULL, 'notebookID' TEXT NOT NULL, 'createdAt' DATE NOT NULL, 'updatedAt' DATE NOT NULL, 'name' TEXT NOT NULL, 'content' TEXT, 'imgArray' BLOB, 'audioArray' TEXT);"];
        
        BOOL result2 = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS Notebook ('ID' TEXT PRIMARY KEY NOT NULL, 'name' TEXT NOT NULL, 'count' INTEGER NOT NULL);"];
        
        if (result1 && result2) {
            NSLog(@"数据库打开成功!");
        }else{
            NSLog(@"数据库打开失败!");
        }
    }
}

#pragma mark --- Notebook

// 新建Notebook
- (void)insertNotebookWithNotebook:(NotebookModel *)notebook{
    
    // 设置ID,createdAt,updatedAt
    notebook.ID = [NSString stringWithFormat:@"notebook%f",[[NSDate date] timeIntervalSince1970]];
    notebook.createdAt = [NSDate dateWithTimeIntervalSince1970:[[notebook.ID substringFromIndex:8] intValue] + 8 * 60 * 60];
    notebook.updatedAt = notebook.createdAt;
    
    if (notebook.name == nil || [notebook.name isEqualToString:@""]) {
        notebook.name = @"未命名笔记本";
    }
    
    
    BOOL result = [db executeUpdate:@"insert into Notebook (ID,name,count) values(?,?,?);",notebook.ID,notebook.name,[NSNumber numberWithInteger:notebook.count]];
    
    //    BOOL result = [db executeUpdate:@"INSERT INTO Notebook (ID, name, num) VALUES (?, ?, ?);",@"abc",@"测试笔记本",10];
    
    if (result) {
        NSLog(@"Notebook插入成功!");
        dispatch_async(dispatch_get_main_queue(), ^{
            self.updateUI();
        });
    }else{
        NSLog(@"Notebook插入失败!");
    }
}

// 根据ID删除Notebook
- (void)deleteNotebookWithNotebookID:(NSString *)ID{
    
    BOOL result = [db executeUpdate:@"delete from Notebook where ID = ?",ID];
    if (result) {
        NSLog(@"Notebook删除成功");
    }else{
        NSLog(@"Notebook删除失败");
    }
}

// 根据ID修改Notebook
- (void)updateNotebookWithNotebookID:(NSString *)ID andNotebook:(NotebookModel *)notebook{
    
    // 更改后,要更改updatedAt
    notebook.updatedAt = [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
    
    if (notebook.name == nil || [notebook.name isEqualToString:@""]) {
        notebook.name = @"未命名笔记本";
    }
    
    BOOL result = [db executeUpdate:@"update Notebook set name = ?, count = ? where ID = ?",notebook.name,[NSNumber numberWithInteger:notebook.count],ID];
    
    if (result) {
        NSLog(@"Notebook更改成功!");
    }else{
        NSLog(@"Notebook更改失败!");
    }
}

//根据ID查询Notebook
- (NotebookModel *)selectNotebookWithNotebookID:(NSString *)ID{
    FMResultSet *result = [db executeQuery:@"SELECT * FROM Notebook where id = ?",ID];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    
    while ([result next]) {
        
        NotebookModel *notebook = [[NotebookModel alloc]init];
        notebook.name = [result stringForColumn:@"name"];
        notebook.ID = [result stringForColumn:@"ID"];
        notebook.count = [result intForColumn:@"count"];
        [array addObject:notebook];
    }
    
    [result close];
    
    if (array.count == 0) {
        NSLog(@"没有查到!");
        return nil;
    }
    
    
    return array[0];
}

// 查询所有Notebook
- (NSMutableArray *)selectAllNotebook{
    FMResultSet *result = [db executeQuery:@"SELECT * FROM Notebook"];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    
    while ([result next]) {
        NotebookModel *notebook = [[NotebookModel alloc]init];
        notebook.name = [result stringForColumn:@"name"];
        notebook.ID = [result stringForColumn:@"ID"];
        notebook.count = [result intForColumn:@"count"];
        [array addObject:notebook];
    }
    [result close];
    
    return array;
}




#pragma mark --- Note

// 往数据库插入model
- (void)insertNoteWithModel:(NoteModel *)model{
    
    // 设置ID,createdAt,updatedAt
    model.ID = [NSString stringWithFormat:@"note%f",[[NSDate date] timeIntervalSince1970]];
    model.createdAt = [NSDate dateWithTimeIntervalSince1970:[[model.ID substringFromIndex:4] intValue] + 8 * 60 * 60];
    // 新建时 最后更新时间 就是创建时间
    model.updatedAt = model.createdAt;
    
    // img 转 imgData
    NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
    for (UIImage *img in model.imgArray) {
        NSData *imgData = UIImageJPEGRepresentation(img, 1);
        [imgDataArray addObject:imgData];
    }
    
    // imgArray归档
    NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:500];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
    [archiver encodeObject:imgDataArray forKey:[NSString stringWithString:model.ID]];
    [archiver finishEncoding];
    if (model.name == nil || [model.name isEqualToString:@""]) {
        model.name = @"未命名笔记";
    }
    BOOL result = [db executeUpdate:@"INSERT INTO note (ID, notebookID,createdAt,updatedAt,name,content,imgArray,audioArray) VALUES (?,?,?,?,?,?,?,?);", model.ID,model.notebookID,model.createdAt,model.updatedAt,model.name,model.content,imgArrayData,nil,nil];
    
    if (result) {
        NSLog(@"插入成功!");
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.updateNoteUI();
//        });
    }else{
        NSLog(@"插入失败!");
    }
    
    
}

// 根据ID查询笔记
- (NoteModel *)selectNoteWithNoteID:(NSString *)ID{
    FMResultSet *result = [db executeQuery:@"SELECT * FROM Note where id = ?",ID];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    
    while ([result next]) {
        
        NoteModel *model = [[NoteModel alloc]init];
        model.name = [result stringForColumn:@"name"];
        model.ID = [result stringForColumn:@"ID"];
        model.notebookID = [result stringForColumn:@"notebookID"];
        model.content = [result stringForColumn:@"content"];
        model.createdAt = [result dateForColumn:@"createdAt"];
        model.updatedAt = [result dateForColumn:@"updatedAt"];
        NSData *imgArrayData = [result dataForColumn:@"imgArray"];
        
        // imgArray反归档
        NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:imgArrayData];
        NSMutableArray *imgDataArray = [unarchiver decodeObjectForKey:model.ID];
        [unarchiver finishDecoding];
        
        // imgData 转 img
        NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:5];
        for (NSData *data in imgDataArray) {
            UIImage *img = [UIImage imageWithData:data];
            [imgArray addObject:img];
        }
        
        model.imgArray = imgArray;
        
        [array addObject:model];
    }
    [result close];
    
    if (array.count == 0) {
        NSLog(@"没有查到!");
        return nil;
    }
    
    return array[0];
}

// 删除笔记
- (void)deleteNoteWithNoteID:(NSString *)ID{
    
    BOOL result = [db executeUpdate:@"delete from Note where ID = ?",ID];
    if (result) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
    
}

// 改
- (void)updateNoteWithNoteID:(NSString *)ID andNote:(NoteModel *)note{
    
    // 更改后,要更改updatedAt
    note.updatedAt = [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
    
    // img 转 imgData
    NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
    for (UIImage *img in note.imgArray) {
        NSData *imgData = UIImageJPEGRepresentation(img, 1);
        [imgDataArray addObject:imgData];
    }
    
    // imgArray归档
    NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:500];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
    [archiver encodeObject:imgDataArray forKey:[NSString stringWithString:note.ID]];
    [archiver finishEncoding];
    
    
    BOOL result = [db executeUpdate:@"update Note set updatedAt = ?, name = ?, content = ?, imgArray = ?, audioArray = ? where ID = ?",note.updatedAt,note.name,note.content,imgArrayData,note.audioArray,ID];
    
    if (result) {
        NSLog(@"更改成功!");
       
    }else{
        NSLog(@"更改失败!");
    }
    
}


// 最后更新时间降序排列
- (NSMutableArray *)orderAllNoteByDescWithNotebookID:(NSString *)notebookID{
    
    FMResultSet *result = [db executeQuery:@"select * from note where notebookID = ? order by updatedAt DESC",notebookID];
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    
    while ([result next]) {
        
        NoteModel *model = [[NoteModel alloc]init];
        model.name = [result stringForColumn:@"name"];
        model.ID = [result stringForColumn:@"ID"];
        model.notebookID = [result stringForColumn:@"notebookID"];
        model.content = [result stringForColumn:@"content"];
        model.createdAt = [result dateForColumn:@"createdAt"];
        model.updatedAt = [result dateForColumn:@"updatedAt"];
        NSData *imgArrayData = [result dataForColumn:@"imgArray"];
        
        // imgArray反归档
        NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:imgArrayData];
        NSMutableArray *imgDataArray = [unarchiver decodeObjectForKey:model.ID];
        [unarchiver finishDecoding];
        
        // imgData 转 img
        NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:5];
        for (NSData *data in imgDataArray) {
            UIImage *img = [UIImage imageWithData:data];
            [imgArray addObject:img];
        }
        
        model.imgArray = imgArray;
        
        [array addObject:model];
    
    }
    [result close];
    
    return array;
    
}

@end
